/**
 * @Author:高志斐
 * @Date:2020/7/8
 * @Description:这是交易详情页面
 */
import React,{Component} from "react";
import {Button, Icon, NavBar, WhiteSpace, List, Modal, Toast} from "antd-mobile";
import axios from 'axios';
import {URL} from "../../index";
import {color} from "echarts/src/export";
import {getCookieId} from "../Login/Component_Login/GetCookie";
const Item = List.Item;
const Brief = Item.Brief;
const alert = Modal.alert;
const transStatus=['赎回确认中','申购确认中','申购成功','撤单成功','赎回成功']
const entrustStatus=['委托失败','处理中','委托成功','委托撤单']
function closest(el, selector) {
    const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
    while (el) {
        if (matchesSelector.call(el, selector)) {
            return el;
        }
        el = el.parentElement;
    }
    return null;
}
export default class TransactionDetail extends Component{
    constructor(props) {
        super(props);
        const tradeId = this.props.location.state.tradeId;
        // const tradeName = this.props.location.state.tradeName;
        // const tradeAmoount = this.props.location.state.tradeAmoount;
        // const tradeCategory = this.props.location.state.tradeCategory;
        // const logicId = this.props.location.state.logicId;
        // const gmtModified = this.props.location.state.gmtModified;
        this.state = {
            entrusts:[],//委托列表
            disabled: false,
            tradeId:tradeId,//交易记录id
            tradeName:"",//组合名称
            tradeAmoount:0,//交易金额
            tradeCategory:"",//交易状态
            logicId:"",//订单编号
            gmtModified:"",//下单时间
            comBaseId:null,
            modal1:false,
            modal2:false,
            modal3:false,
        }
        this.cancelOrder=this.cancelOrder.bind(this)
        this.doCancel=this.doCancel.bind(this)
    }
    //加载交易详情数据
    loadTrans(){
        axios({
            method:"GET",
            url:URL + "/tradeRecord/tradeRecordLists",
            params:{
                tradeId: this.state.tradeId,
                userId: getCookieId()
            }
        }).then(res=>{
            this.setState({
                tradeName:res.data.tradeRecords[0].comBaseName,
                tradeAmoount:res.data.tradeRecords[0].tradeAmoount,
                tradeCategory:transStatus[res.data.tradeRecords[0].tradeCategory],
                logicId:res.data.tradeRecords[0].logicId,
                gmtModified:res.data.tradeRecords[0].gmtModified,
                comBaseId:res.data.tradeRecords[0].comBaseId
            })
        }).catch(error =>{
            console.log(error)
        })
    }
    //加载委托列表数据
    loadEntrust(){
        axios({
            method:"GET",
            url:URL + "/entrustRecord/getEntrustRecordByTradeId",
            params:{tradeId: this.state.tradeId}
        }).then(res=>{
            this.setState({
                entrusts:this.state.entrusts.concat(res.data.entrustList)
            })
        }).catch(error =>{
            console.log(error)
        })
    }
    //弹出提示框
    showModal = key => (e) => {
        e.preventDefault(); // 修复 Android 上点击穿透
        this.setState({
            [key]: true,
        });
    }
    //关闭提示框
    onClose = key => () => {
        this.setState({
            [key]: false,
        });
    }
    onWrapTouchStart = (e) => {
        // fix touch to scroll background page on iOS
        if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
            return;
        }
        const pNode = closest(e.target, '.am-modal-content');
        if (!pNode) {
            e.preventDefault();
        }
    }
    cancelOrder(){
        //0 赎回确认中,可撤销赎回单
        if (this.state.tradeCategory==="赎回确认中"){
            alert(
                "撤单确认",
                "撤单后本次赎回将取消，确认撤单吗？",
                [
                    {text:'确认',onPress:()=>this.doCancel(1)},
                    {text:'取消',onPress:()=> console.log('取消')},
                ])
        }
        //1 申购确认中，可撤销买入单
        else if(this.state.tradeCategory==="申购确认中"){
            alert(
                "撤单确认",
                "撤单后本次买入将取消，资金将于24小时内到账，确认撤单吗？",
                [
                    {text:'确认',onPress:()=>this.doCancel(0)},
                    {text:'取消',onPress:()=> console.log('取消')},
                ])
        }
        //2 申购成功，不可撤单
        else if(this.state.tradeCategory==="申购成功"){
            // this.showModal('modal1')
            Toast.info("此交易单已申购成功，无法撤单，您可选择赎回")
        }
        //3 撤单成功
        else if(this.state.tradeCategory==="撤单成功"){
            // this.showModal('modal2')
            Toast.info("此交易单已撤单成功!")
        }
        //4 赎回成功，无法撤单
        else if(this.state.tradeCategory==="赎回成功"){
            // this.showModal('modal3')
            Toast.info("此交易单已赎回成功，无法撤单！")
        }else{
            console.log(this.state.tradeCategory)
        }

    }
    //撤单
    doCancel(t){
        axios({
            method:"GET",
            url: URL + "/transaction/cancelOrder",
            params: {
                userId:getCookieId(),
                comBaseId:this.state.comBaseId,
                type:t
            }
        }).then(res => {
            if (res.data.code === 200) {
                Toast.info("撤单成功！")
                window.location.reload();
            }else{
                console.log(res.data)
            }
        })
    }

    componentDidMount() {
        this.loadEntrust()
        this.loadTrans()
    }
    render() {
        return(
            <div>
                <NavBar
                    mode="light"
                    icon={<Icon type="left" style={{color:"#f8a83f"}}/>}
                    onLeftClick={
                        ()=> {this.props.history.push('/transactionRecord')}
                    }
                >交易详情
                </NavBar>
                <WhiteSpace/>
                <div className='transactionDetail-div' style={{backgroundColor:"white"}}>
                    <span style={{color:'#9f9f9f'}}>组合名称</span>&nbsp;&nbsp;<span>{this.state.tradeName}</span>
                </div>
                <div className='transactionDetail-div'>
                    <span style={{color:'#9f9f9f'}}>交易金额</span>&nbsp;&nbsp;<span>{this.state.tradeAmoount}&nbsp;&nbsp;元</span>
                </div>
                <div className='transactionDetail-div' style={{backgroundColor:"white"}}>
                    <span style={{color:'#9f9f9f'}}>交易状态</span>&nbsp;&nbsp;<span>{this.state.tradeCategory}</span>
                </div>
                <div className='transactionDetail-div'>
                    <span style={{color:'#9f9f9f'}}>下单时间</span>&nbsp;&nbsp;<span>{String(this.state.gmtModified).substring(0,String(this.state.gmtModified).length-2)}</span>
                </div>
                <div className='transactionDetail-div' style={{backgroundColor:"white"}}>
                    <span style={{color:'#9f9f9f'}}>订单编号</span>&nbsp;&nbsp;<span>{this.state.logicId}</span>
                </div>
                <List renderHeader={() => '委托列表'} className="my-list">
                    {(()=>{return this.state.entrusts.map((item,index)=>{
                        return(
                            <Item multipleLine extra={item.entrustAmount+' 元'}>
                                {item.proName}&nbsp;({item.proTsCode}) <Brief>{entrustStatus[item.entrustStatus]}</Brief>
                            </Item>
                    )
                    })
                    })()}
                </List>
                <WhiteSpace/>
                <WhiteSpace/>
                <WhiteSpace/>
                <div className='wallet-num-container' style={{height:'30px'}}>
                <a style={{ display: 'block', marginBottom: 20, color: '#f8a83f',fontSize:'16px' }}
                   onClick={this.cancelOrder}
                >
                    撤单
                </a>
                </div>
                {/*modal1 对应申购成功状态*/}
                <Modal
                    visible={this.state.modal1}
                    transparent
                    maskClosable={false}
                    title="撤单失败"
                    footer={[{ text: '确定' , onPress: () => { this.onClose('modal1')(); }}]}
                    onClose={this.onClose('modal1')}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                >
                    此交易单已申购成功，无法撤单，您可选择赎回
                </Modal>
                {/*modal2 对应撤单成功状态*/}
                <Modal
                    visible={this.state.modal2}
                    transparent
                    maskClosable={false}
                    title="撤单失败"
                    footer={[{ text: '确定' , onPress: () => { this.onClose('modal2')(); }}]}
                    onClose={this.onClose('modal2')}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                >
                    此交易单已撤单成功!
                </Modal>
                {/*modal3 对应赎回成功状态*/}
                <Modal
                    visible={this.state.modal3}
                    transparent
                    maskClosable={false}
                    title="撤单失败"
                    footer={[{ text: '确定' , onPress: () => { this.onClose('modal3')(); }}]}
                    onClose={this.onClose('modal3')}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                >
                    此交易单已赎回成功，无法撤单！
                </Modal>
            </div>
        );
    }
}
